/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.bezrabotnih.cabinet.client.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import net.bezrabotnih.cabinet.client.place.FindJobPlace;
import net.bezrabotnih.cabinet.client.place.MenuItemPlace;
import net.bezrabotnih.cabinet.client.place.PerformerJobsPlace;
import net.bezrabotnih.cabinet.client.place.ProviderJobsPlace;
import net.bezrabotnih.cabinet.client.request.CabinetApplicationRequest;
import net.bezrabotnih.cabinet.client.request.CabinetJobRequest;
import net.bezrabotnih.cabinet.client.request.CabinetRequestFactory;
import net.bezrabotnih.cabinet.client.ui.PerformerJobsView;
import net.bezrabotnih.cabinet.client.ui.PerformerJobBlockView;
import net.bezrabotnih.cabinet.client.ui.PerformerJobsViewImpl;
import net.bezrabotnih.cabinet.client.ui.ProviderJobsViewImpl;
import net.bezrabotnih.client.managed.request.ApplicationProxy;
import net.bezrabotnih.client.managed.request.JobProxy;
import net.bezrabotnih.client.managed.request.JobTypeProxy;
import net.bezrabotnih.client.managed.request.UserAccountProxy;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.requestfactory.shared.Request;
import com.google.gwt.requestfactory.shared.ServerFailure;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

/**
 * Activities are started and stopped by an ActivityManager associated with a container Widget.
 */
public class PerformerJobsActivity extends AbstractActivity implements PerformerJobsView.Presenter,PerformerJobBlockView.Presenter{

	private static final Logger log = Logger.getLogger(PerformerJobsActivity.class.getName());
	/**
	 * Sample property.
	 */
	private String name;
	private MenuItemPlace place;
	private CabinetRequestFactory requestFactory;
	private PlaceController placeController;
	private PerformerJobsView view;
	
	private UserAccountProxy currentUserAccountProxy;
	
	private List<JobProxy> jobProxies; 
	
	private List<ApplicationProxy> applicationProxies;
	
	

	public PerformerJobsActivity(MenuItemPlace place,CabinetRequestFactory requestFactory,PlaceController placeController) {
		this.place=place;
		this.requestFactory=requestFactory;
		this.placeController=placeController;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		this.view = new PerformerJobsViewImpl();
		view.setPresenter(this);
		containerWidget.setWidget(view.asWidget());

		requestFactory.cabinetUserAccountRequest().currentUserAccount().fire(new Receiver<UserAccountProxy>() {

			@Override
			public void onSuccess(final UserAccountProxy userAccountProxy) {

				PerformerJobsActivity.this.currentUserAccountProxy=userAccountProxy;

				Request<List<JobProxy>> jobsRequest=null;

				if (place instanceof PerformerJobsPlace) {
					jobsRequest=requestFactory.cabinetJobRequest().findJobsByWinnerId(userAccountProxy.getId()).with("jobType");
					view.setTitle("Мои работы");
				}
				else if (place instanceof FindJobPlace){
					jobsRequest=requestFactory.cabinetJobRequest().findAvailableJobsByPerformerId(userAccountProxy.getId()).with("jobType");
					view.setTitle("Новые работы");
				}

				if (jobsRequest!=null)
					jobsRequest.fire(new Receiver<List<JobProxy>>() {


						public void onSuccess(final List<JobProxy> jobProxies) {

							PerformerJobsActivity.this.jobProxies=jobProxies;

							if (PerformerJobsActivity.this.jobProxies!=null){

								List<String> jobIds=new ArrayList<String>();
								for (JobProxy jobProxy:jobProxies) jobIds.add(jobProxy.getId());

										requestFactory.cabinetApplicationRequest().findApplicationsAmongAppliedBy(jobIds, currentUserAccountProxy.getId()).fire(new Receiver<List<ApplicationProxy>>() {

											@Override
											public void onSuccess(List<ApplicationProxy> applicationProxies) {
												PerformerJobsActivity.this.applicationProxies=applicationProxies;

												int proxyCount=PerformerJobsActivity.this.jobProxies.size();
												for (int i=0;i<proxyCount;i++){
													JobProxy jobProxy=jobProxies.get(proxyCount-1-i);

													view.addJobBlock(PerformerJobsActivity.this, 
															jobProxy.getId(),
															jobProxy.getName(),
															jobProxy.getJobType().getName(),
															jobProxy.getProviderId(),
															jobProxy.getIsHourly(),
															jobProxy.getStartDate(),
															jobProxy.getDeadLine(),
															jobProxy.getPrice(),
															jobProxy.getDescription(),
															jobProxy.getApplicantIds().contains(currentUserAccountProxy.getId()),
															currentUserAccountProxy.getId().equals(jobProxy.getWinnerId()));

												}



											}


										});






							}
						}
					});

			}
		});

	}

	@Override
	public String mayStop() {
		return null;
	}

	/**
	 * @see PerformerJobsView.Presenter#goTo(Place)
	 */
	public void goTo(Place place) {
		// TODO
	}

	@SuppressWarnings("deprecation")
	@Override
	public void jobDetailsClicked(final String jobId) {
		
		final JobProxy jobProxy=findJobProxyById(jobId);

		requestFactory.cabinetUserAccountRequest().findUserAccount(jobProxy.getProviderId()).fire(new Receiver<UserAccountProxy>() {

			@Override
			public void onSuccess(UserAccountProxy userAccountProxy) {
				
				String phone="";
				if (currentUserAccountProxy.getId().equals(jobProxy.getWinnerId())) phone="&nbsp;&nbsp; тел. "+userAccountProxy.getPhoneNumber();
				
				view.setProviderName(userAccountProxy.getName()+phone, jobId);
				
			}
		});
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void applyTo(final String jobProxyId) {
		final JobProxy originalJobProxy=findJobProxyById(jobProxyId);
		if (currentUserAccountProxy!=null&&originalJobProxy!=null){
			log.info("creating new application");
			    CabinetApplicationRequest applicationRequest=requestFactory.cabinetApplicationRequest();
			    ApplicationProxy applicationProxy=applicationRequest.create(ApplicationProxy.class);
			    applicationProxy.setJobId(jobProxyId);
			    applicationProxy.setUserAccountId(currentUserAccountProxy.getId());
			    log.info("application userAccountId="+applicationProxy.getUserAccountId());
			
			    applicationRequest.persist().using(applicationProxy).fire(new Receiver<Void>() {

					@Override
					public void onSuccess(Void response) {
						view.setApplicationSuccessView(jobProxyId);
						originalJobProxy.getApplicantIds().add(currentUserAccountProxy.getId());
						
					}
					@Override
					public void onFailure(ServerFailure error) {
						log.info("Application persist error:"+error.getMessage());
						view.setApplicationFailureView(jobProxyId);
					}
				});
				
			}else {
			if (originalJobProxy==null)  {
				Window.alert("Данная заявка устарела");
				view.setApplicationFailureView(jobProxyId);
			}
		}	
			
			
		
		
	}
	@SuppressWarnings("deprecation")
	@Override
	public void cancelApplication(final String jobProxyId) {
		final JobProxy originalJobProxy=findJobProxyById(jobProxyId);
		if (currentUserAccountProxy!=null&&originalJobProxy!=null){
			
			CabinetApplicationRequest applicationRequest=requestFactory.cabinetApplicationRequest();
		
			applicationRequest.deleteApplications(jobProxyId, currentUserAccountProxy.getId()).fire(new Receiver<Void>() {

					@Override
					public void onSuccess(Void response) {
						view.setApplicationCancelSuccessView(jobProxyId);
						originalJobProxy.getApplicantIds().remove(currentUserAccountProxy.getId());
					}
					@Override
					public void onFailure(ServerFailure error) {
						view.setApplicationCancelSuccessView(jobProxyId);
					}
				});
			}else{
			Window.alert("Данная заявка устарела и не может быть отменена");
			view.setApplicationCancelSuccessView(jobProxyId);
		}
			
		
		
	}
    
	private JobProxy findJobProxyById(String id){
	if (jobProxies!=null)
		for (JobProxy proxy:jobProxies){
			if (id.equals(proxy.getId())) return proxy;
		}
		return null;
	}
	
	private ApplicationProxy findApplicationProxyById(String id){
		if (applicationProxies!=null)
			for (ApplicationProxy proxy:applicationProxies){
				if (id.equals(proxy.getId())) return proxy;
			}
			return null;
		}


	@Override
	public UserAccountProxy getCurrentUserAccountProxy() {
		// TODO Auto-generated method stub
		return null;
	}
	

}
